package hutool.http;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * @author ZhuQi
 * @ClassName HttpTestDemo
 * @Date 2022/9/5 11:20
 * @Version 1.0
 * @Description 测试hutool HTTP 工具类
 */
public class HttpTestDemo {

    @SneakyThrows
    public static void main(String[] args) {
        String url = "http://192.168.3.41:9099/device/transitController/payNotify";
        HashMap<String, Object> param = new HashMap<>();
        param.put("uniqueId", UUID.fastUUID().toString());
        param.put("payResult", "1111");
        String JsonStr = JSONUtil.toJsonStr(param);
        System.out.println(JsonStr);
        String encrypt = encrypt(JsonStr, KEY);

        // 构建请求参数map
        HashMap<String, Object> map = new HashMap<>();
        map.put("notifyParamVo", encrypt);

        String post = HttpUtil.post(url, map);
        System.out.println(post);
    }

    //公钥
    private static final String KEY = "1234567811345678";

    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);

    }

    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

}
